<template>
  <div class="app-container">
    <el-form :inline="true">
      <template v-if="showSearch">
        <el-form-item :label="$t('startDate')">
          <el-date-picker
            v-model="startDate"
            clearable
            type="datetime"
            :placeholder="$t('startDate')"
            :picker-options="pickerOptions1"
            value-format="timestamp"
          />
        </el-form-item>
        <el-form-item :label="$t('endDate')">
          <el-date-picker
            v-model="endDate"
            clearable
            type="datetime"
            :placeholder="$t('endDate')"
            :picker-options="pickerOptions1"
            value-format="timestamp"
          />
        </el-form-item>
        <el-form-item :label="$t('deviceCore')">
          <el-input v-model="deviceCore" clearable :placeholder="$t('deviceCore')"/>
        </el-form-item>
        <el-form-item :label="$t('status')">
          <el-select v-model="status" @change="pageGetDeviceStatus">
            <el-option
              :label="$t('all')"
              :value="null"
            />
            <el-option
              :label="$t('ONLINE')"
              value="ONLINE"
            />
            <el-option
              :label="$t('OFFLINE')"
              value="OFFLINE"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="pageGetDeviceStatus"
          >{{ $t('search') }}
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-sold-out"
            @click="downloadExcel"
          >{{ $t('download') }}
          </el-button>
          <el-button
            v-if="deviceCore!=null"
            type="primary"
            icon="el-icon-sold-out"
            @click="goToChart"
          >{{ $t('chart') }}
          </el-button>
        </el-form-item>
        <el-form-item v-if="devModel">
          <el-button
            v-show="mList.length > 0"
            icon="el-icon-delete"
            type="danger"
            @click="mDel"
          >{{ $t('delete') }}
          </el-button>
        </el-form-item>
      </template>
      <el-form-item>
        <el-button icon="el-icon-search" circle @click="showSearch=!showSearch"/>
      </el-form-item>
    </el-form>

    <el-table
      ref="multipleTable"
      v-loading="loading"
      :data="onlineList"
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50"/>
      <el-table-column :label="$t('device')+$t('name')">
        <template slot-scope="scope">
          <router-link
            :to="{ path:'/device/manage/'+scope.row.deviceCore ,query:{'deviceCore':scope.row.deviceCore}}"
          >
            <i>{{ scope.row.deviceName }} ({{ scope.row.deviceCore }})</i>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('time')" sortable width="200">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span style="margin-left: 13px">{{ formatDate(scope.row.timestamp) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" :label="$t('status')" sortable width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status=='ONLINE'?'success':'danger'">{{
              formatDeviceStatus(scope.row.status)
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="devModel" :label="$t('function')" width="120">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-delete"
            @click="del(scope.row)"
          >{{ $t('delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="text-align:right;margin: 15px 0">
      <el-pagination
        background
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      :visible.sync="showChart"
      destroy-on-close
      width="800px"
      top="5vh"
    >
      <status-month-count :chart-data="chartData"/>
    </el-dialog>

  </div>
</template>

<script>
import { cancelNotice, failureNotice, formatDate, formatDeviceStatus } from '@/util/common'
import {
  deleteDeviceStatusList,
  deleteStatusError,
  listDeviceStatus,
  monthCount,
  pageGetDeviceStatus
} from '@/api/iot/iotDeviceStatusApi'
import { getCompanyId, getDeptId, getDevModel, getPageSize, setPageSize } from '@/util/storage'
import StatusMonthCount from '@/components/StatusMonthCount'
import { downloadExcel } from '@/util/file'

export default {
  name: 'DeviceStatus',
  components: {
    StatusMonthCount
  },
  data() {
    return {
      companyId: getCompanyId(),
      downloadColumnNameList: [],
      downloadData: [],
      showSearch: true,
      onlineList: [],
      nowPage: 1,
      currentPage: 1,
      total: 0,
      pageSize: getPageSize(),
      loading: true,
      mList: [],
      startDate: 0,
      endDate: 0,
      pickerOptions1: {
        shortcuts: [
          {
            text: this.$t('today'),
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: this.$t('today'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: this.$t('a') + this.$t('week') + this.$t('ago'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      deviceName: null,
      deviceCore: null,
      showChart: false,
      chartData: null,
      status: null,
      deptId: null,
      devModel: getDevModel() === 'true'
    }
  },
  mounted() {
    const param = this.$route.query
    if (param != null) {
      this.deviceCore = param.deviceCore
      this.deviceName = param.deviceName
      if (this.deviceName) {
        this.setTagsViewTitle()
      }
      if (param.companyId) {
        this.companyId = parseInt(param.companyId)
      }
      if (param.isDept && param.isDept === '1') {
        this.deptId = parseInt(getDeptId())
      }
    }
    const timestamp = new Date().getTime() + 5 * 60 * 60 * 1000
    this.startDate = new Date().getTime() - 7 * 24 * 60 * 60 * 1000
    this.endDate = timestamp
    this.pageGetDeviceStatus()
  },
  methods: {
    formatDate(time) {
      return formatDate(this, time)
    },
    formatDeviceStatus(status) {
      return formatDeviceStatus(this, status)
    },
    setTagsViewTitle() {
      this.tempRoute = Object.assign({}, this.$route)
      const route = Object.assign({}, this.tempRoute, {
        title: `${this.deviceName}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    goToChart() {
      const data = {
        deviceCore: this.deviceCore
      }
      monthCount(data).then(res => {
        if (res.code === '200') {
          this.chartData = res.data
          this.showChart = true
        }
      })
    },
    downloadExcel() {
      if (!this.startDate || this.startDate === 0) {
        failureNotice(this, this.$t('time'))
        return
      }
      if (!this.endDate || this.endDate === 0) {
        failureNotice(this, this.$t('time'))
        return
      }
      this.loading = true
      const data = {
        pageSize: this.pageSize,
        currentPage: this.currentPage,
        startDate: Math.round(this.startDate / 1000),
        endDate: Math.round(this.endDate / 1000),
        status: this.status,
        companyId: this.companyId
      }
      if (this.deviceCore) {
        data.deviceCore = this.deviceCore
      }
      listDeviceStatus(data).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.loading = false
          this.downloadColumnNameList = [this.$t('device')+this.$t('name'), this.$t('deviceCore'), this.$t('status'), this.$t('date')]
          const downloadData = []
          data.forEach(status => {
            downloadData.push({
              deviceName: status.deviceName,
              deviceCore: status.deviceCore,
              status: formatDeviceStatus(this, status.status),
              date: formatDate(this, status.timestamp)
            })
          })
          this.downloadData = downloadData
          downloadExcel(this.deviceName + '-' + this.$t('device') + this.$t('status'), this.downloadColumnNameList, this.downloadData)
        }
      })
    },
    handleSelectionChange(val) {
      const mList = []
      val.forEach(function(row) {
        mList.push(row.statusId)
      })
      this.mList = mList
    },
    mDel() {
      const that = this
      this.$confirm(this.$t('deletePrompt'), this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteDeviceStatusList({
            idList: that.mList
          }).then(res => {
            const { code } = res
            if (code === '200') {
              that.pageGetDeviceStatus()
            }
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    del(index) {
      const that = this
      this.$confirm(this.$t('deletePrompt'), this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteStatusError({
            statusId: index.statusId
          }).then(res => {
            const { code } = res
            if (code === '200') {
              that.pageGetDeviceStatus()
            }
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    handleSizeChange(val) {
      this.pageSize = val
      setPageSize(this.pageSize)
      this.pageGetDeviceStatus()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.pageGetDeviceStatus()
    },
    pageGetDeviceStatus() {
      this.loading = true
      const startDate = Math.round(this.startDate / 1000)
      const endDate = Math.round(this.endDate / 1000)
      const data = {
        deptId: this.deptId,
        pageSize: this.pageSize,
        currentPage: this.currentPage,
        status: this.status,
        companyId: this.companyId,
        startDate: startDate === 0 ? null : startDate,
        endDate: endDate === 0 ? null : endDate
      }
      if (this.deviceCore) {
        data.deviceCore = this.deviceCore
      }
      pageGetDeviceStatus(data).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.loading = false
          this.total = data.total
          this.onlineList = data.data
        }
      })
    }
  }
}
</script>

